package cn.accjiyun.pki.controller.system;

import cn.accjiyun.pki.common.controller.BaseController;
import cn.accjiyun.pki.common.entity.PageModel;
import cn.accjiyun.pki.common.entity.QueryEntity;
import cn.accjiyun.pki.common.utils.MD5;
import cn.accjiyun.pki.common.utils.SingletonLoginUtils;
import cn.accjiyun.pki.entity.SystemUser;
import cn.accjiyun.pki.service.SystemUserService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/18.
 */
@Controller
@RequestMapping("/admin/system")
public class AdminSystemUserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminSystemUserController.class);

    private static String addSysUserPage = getViewPath("/admin/system/sys-user-add");
    private static String sysUserListPage = getViewPath("/admin/system/sys-user-list");
    private static String userPassPage = getViewPath("/admin/system/sys-user-update");

    @Autowired
    private SystemUserService systemUserService;

    @InitBinder({"systemUser"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("systemUser.");
    }

    /**
     * 创建用户
     *
     * @param systemUser 用户实体
     * @return Map<String,Object>
     */
    @RequestMapping("/createSystemUser")
    @ResponseBody
    public String createSysUser(HttpServletRequest request,
                                @ModelAttribute("systemUser") SystemUser systemUser) {
        try {
            boolean isValidate = systemUserService.validateLoginName(request.getParameter("loginName"));
            if (!isValidate) {
                return getReturnJson(400, "用户名已存在！", null);
            }
            systemUser.setLoginName(systemUser.getLoginName().trim());
            systemUser.setPassword(MD5.getMD5(systemUser.getPassword()));
            systemUserService.createSystemUser(systemUser);
        } catch (Exception e) {
            logger.error("AdminSocietyUser.createSysUser()--error", e);
            return getReturnJson(400, "添加失败", null);
        }
        return getReturnJson(200, "添加成功", "/admin/system/userList");
    }

    @RequestMapping("/validateLoginName")
    @ResponseBody
    public String validateLoginName(HttpServletRequest request) {
        try {
            boolean isValidate = systemUserService.validateLoginName(request.getParameter("loginName"));
            if (!isValidate) {
                return getReturnJson(400, "用户名已存在", null);
            }
        } catch (Exception e) {
            logger.error("AdminSocietyUser.validateLoginName()--error", e);
            return getReturnJson(200, "验证出错！", null);
        }
        return getReturnJson(200, "用户名有效", null);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] userIdsString = request.getParameter("id").split(",");
            int[] userIds = new int[userIdsString.length];
            for (int i = 0; i < userIdsString.length; i++) {
                int userId = Integer.valueOf(userIdsString[i]);
                if (isIllegalForAdmin(userId, resultJson)) {
                    return gson.toJson(resultJson);
                }
                userIds[i] = userId;
            }
            if (userIdsString != null && userIdsString.length > 0) {
                systemUserService.deleteSystemUser(userIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getUserList")
    @ResponseBody
    public String getUserList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map eqParams = new HashMap();
            Map likeStrings = new HashMap();
            String disabledString = request.getParameter("disabled");
            String roleIdString = request.getParameter("roleId");
            String keyword = request.getParameter("keyword");
            if (disabledString != null && !disabledString.equals("-1")) {
                eqParams.put("disabled", Byte.valueOf(request.getParameter("disabled")));
            }
            if (roleIdString != null && !roleIdString.equals("-1")) {
                eqParams.put("userRoleByRoleId.roleId", Integer.valueOf(roleIdString));
            }
            likeStrings.put("username", keyword);
            likeStrings.put("loginName", keyword);
            queryEntity.setEqParams(eqParams);
            queryEntity.setLikeStrings(likeStrings);
            PageModel<SystemUser> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<SystemUser> systemUserList = systemUserService.querySystemUserPage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (SystemUser user : systemUserList) {
                JsonObject list = new JsonObject();
                list.addProperty("id", user.getId());
                list.addProperty("loginName", user.getLoginName());
                list.addProperty("disabled", user.getDisabled());
                list.addProperty("username", user.getUsername());
                list.addProperty("identityCard", user.getIdentityCard());
                list.addProperty("mobile", user.getMobile());
                list.addProperty("pukUrl", user.getPukUrl());
                list.addProperty("roleId", user.getUserRoleByRoleId().getRoleId());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminSocietyUser.getUserList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(HttpServletRequest request, SystemUser systemUser) {
        JsonObject resultJson = new JsonObject();
        try {
            if (isIllegalForAdmin(systemUser.getId(), resultJson)) {
                return gson.toJson(resultJson);
            }
            int roleId = Integer.valueOf(request.getParameter("roleId"));
            if (roleId == 0 || roleId == 1) {
                systemUser.setUserRoleByRoleId(systemUserService.queryUserRoleById(roleId));
            }
            SystemUser old = systemUserService.querySystemUserById(systemUser.getId());
            systemUser.setPassword(old.getPassword());

            systemUserService.updateSystemUser(systemUser);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.update()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 更新用户禁用状态
     * @param request
     * @return Json数据
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    public String updateStatus(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int id = Integer.valueOf(request.getParameter("id"));
            byte disabled = 0;
            if (request.getParameter("disabled").equals("false")) {
                disabled = 1;
            }
            if (isIllegalForAdmin(id, resultJson) && disabled == 1) {
                resultJson.addProperty("url", "reload");
                logger.info(gson.toJson(resultJson));
                return gson.toJson(resultJson);
            }
            SystemUser systemUser = systemUserService.querySystemUserById(id);
            systemUser.setDisabled(disabled);
            systemUserService.updateSystemUser(systemUser);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.updateStatus()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
            resultJson.addProperty("url", "reload");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 修改用户密码
     *
     * @return Map<String, Object>
     */
    @RequestMapping("/updatePWD/{id}")
    @ResponseBody
    public String updatePWD(HttpServletRequest request, @PathVariable("id") int id) {
        JsonObject resultJson = new JsonObject();
        try {
            String password = request.getParameter("password");
            if (id == SingletonLoginUtils.getLoginSystemUserId(request) &&
                    id > 0 && password != null && password.trim().length() > 0) {
                SystemUser systemUser = systemUserService.querySystemUserById(id);
                systemUser.setPassword(MD5.getMD5(password));
                systemUserService.updateSystemUser(systemUser);

                resultJson.addProperty("status", 200);
                resultJson.addProperty("msg", "密码修改成功");
            } else {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "你无权操作！");
            }
        } catch (Exception e) {
            logger.error("UserController.updatePWD()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    public boolean isIllegalForAdmin(int userId, JsonObject resultJson) {
        if (userId == 1) {
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "不能对管理员账号操作！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 初始化修改页面
     */
    @RequestMapping("/initUserUpdatePage")
    public ModelAndView initUserUpdatePage(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        model.setViewName(userPassPage);
        SystemUser systemUser = systemUserService.querySystemUserById(SingletonLoginUtils.getLoginSystemUserId(request));
        model.addObject("systemUser", systemUser);
        return model;
    }

    @RequestMapping("/userAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.setViewName(addSysUserPage);
        return model;
    }

    @RequestMapping("/userList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.setViewName(sysUserListPage);
        return model;
    }

}
